package flc.ast.activity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.activity.OnBackPressedCallback;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.imgedit.EditType;
import com.stark.imgedit.model.FuncBean;
import com.stark.imgedit.view.CropImageView;
import com.stark.imgedit.view.CustomPaintView;
import com.stark.imgedit.view.MosaicPaintView;
import com.stark.imgedit.view.RotateImageView;
import com.stark.imgedit.view.StickerView;
import com.stark.imgedit.view.TextStickerView;
import com.stark.imgedit.view.imagezoom.ImageViewTouch;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.BaseEditFragment;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityPicEditBinding;
import flc.ast.fragment.edit.AddTextFragment;
import flc.ast.fragment.edit.BeautyFragment;
import flc.ast.fragment.edit.ColorTuneFragment;
import flc.ast.fragment.edit.CropFragment;
import flc.ast.fragment.edit.EnhanceFragment;
import flc.ast.fragment.edit.FilterFragment;
import flc.ast.fragment.edit.PaintFragment;
import flc.ast.fragment.edit.RotateFragment;
import flc.ast.fragment.edit.StickerFragment;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;

public class PicEditActivity extends BaseAc<ActivityPicEditBinding> {

    public static final int MODE_NONE = 0;
    public static final int MODE_BEAUTY = 7;// 美颜模式
    public static final int MODE_FILTER = 2;// 滤镜模式
    public static final int MODE_ENHANCE = 10;// 图片增强
    public static final int MODE_PAINT = 6;//画笔模式
    public static final int MODE_STICKERS = 1;// 贴图模式
    public static final int MODE_COLOR_TUNE = 8;//色调模式
    public static final int MODE_TEXT = 5;// 文字模式
    public static final int MODE_ROTATE = 4;// 旋转模式
    public static final int MODE_CROP = 3;// 剪裁模式

    public static String sImgPath;
    public static Bitmap sBitmap;
    public static int pos;
    private int oldPosition;
    private EditType mEditType = EditType.MAIN;
    private Bitmap mRetBitmap;
    private List<FuncBean> mFuncItems;
    public int mode = MODE_NONE;// 当前操作模式

    public ImageViewTouch mImgView;
    public CropImageView mCropView;
    public RotateImageView mRotateImageView;
    public MosaicPaintView mMosaicPaintView;
    public CustomPaintView mPaintView;
    public StickerView mStickerView;
    public TextStickerView mTextStickerView;

    private BeautyFragment mBeautyFragment;
    private FilterFragment mFilterFragment;
    private EnhanceFragment mEnhanceFragment;
    private PaintFragment mPaintFragment;
    private StickerFragment mStickerFragment;
    private ColorTuneFragment mColorTuneFragment;
    private AddTextFragment mAddTextFragment;
    private RotateFragment mRotateFragment;
    private CropFragment mCropFragment;

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_edit;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivPicEditBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                switch (mode) {
                    case MODE_BEAUTY:
                        mBeautyFragment.backToMain();
                        return;
                    case MODE_FILTER:
                        mFilterFragment.backToMain();
                        return;
                    case MODE_ENHANCE:
                        mEnhanceFragment.backToMain();
                        return;
                    case MODE_PAINT:
                        mPaintFragment.backToMain();
                        return;
                    case MODE_STICKERS:
                        mStickerFragment.backToMain();
                        return;
                    case MODE_COLOR_TUNE:
                        mColorTuneFragment.backToMain();
                        return;
                    case MODE_TEXT:
                        mAddTextFragment.backToMain();
                        return;
                    case MODE_ROTATE:
                        mRotateFragment.backToMain();
                        return;
                    case MODE_CROP:
                        mCropFragment.backToMain();
                        return;
                    default:
                        break;
                }
                finish();
            }
        });

        mDataBinding.tvPicEditSave.setOnClickListener(this);
        mDataBinding.ivCancel.setOnClickListener(this);
        mDataBinding.ivApply.setOnClickListener(this);
        mDataBinding.tvPicBeauty.setOnClickListener(this);
        mDataBinding.tvPicFilter.setOnClickListener(this);
        mDataBinding.tvPicEnhance.setOnClickListener(this);
        mDataBinding.tvPicPaint.setOnClickListener(this);
        mDataBinding.tvPicSticker.setOnClickListener(this);
        mDataBinding.tvPicColorTune.setOnClickListener(this);
        mDataBinding.tvPicText.setOnClickListener(this);
        mDataBinding.tvPicRotate.setOnClickListener(this);
        mDataBinding.tvPicCrop.setOnClickListener(this);

        mImgView = mDataBinding.imageViewTouch;
        mCropView = mDataBinding.cropImgView;
        mRotateImageView = mDataBinding.myRotateView;
        mMosaicPaintView = mDataBinding.mosaicPaintView;
        mStickerView = mDataBinding.stickerView;
        mTextStickerView = mDataBinding.txtStickerView;
        mPaintView = mDataBinding.customPaintView;
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.tvPicBeauty) {//美颜
            oldPosition = pos;
            pos = 0;
            showFragmentByFunc(mFuncItems.get(0));
        } else if (id == R.id.tvPicFilter) {//滤镜
            oldPosition = pos;
            pos = 1;
            showFragmentByFunc(mFuncItems.get(1));
        } else if (id == R.id.tvPicEnhance) {//画质增强
            oldPosition = pos;
            pos = 2;
            showFragmentByFunc(mFuncItems.get(2));
        } else if (id == R.id.tvPicPaint) {//画笔
            oldPosition = pos;
            pos = 3;
            showFragmentByFunc(mFuncItems.get(3));
        } else if (id == R.id.tvPicSticker) {//贴纸
            oldPosition = pos;
            pos = 4;
            showFragmentByFunc(mFuncItems.get(4));
        } else if (id == R.id.tvPicColorTune) {//色调
            oldPosition = pos;
            pos = 5;
            showFragmentByFunc(mFuncItems.get(5));
        } else if (id == R.id.tvPicText) {//文字
            oldPosition = pos;
            pos = 6;
            showFragmentByFunc(mFuncItems.get(6));
        } else if (id == R.id.tvPicRotate) {//旋转
            oldPosition = pos;
            pos = 7;
            showFragmentByFunc(mFuncItems.get(7));
        } else if (id == R.id.tvPicCrop) {//裁剪
            oldPosition = pos;
            pos = 8;
            showFragmentByFunc(mFuncItems.get(8));
        } else if (id == R.id.tvPicEditSave) {//保存
            oldPosition = pos;
            pos = 9;
            saveImg();
        } else if (id == R.id.ivCancel) {//取消
            cancelEdit();
            mDataBinding.rlTitle.setVisibility(View.VISIBLE);
            mDataBinding.rlFunction.setVisibility(View.GONE);
        } else if (id == R.id.ivApply) {//确定
            clickApply();
        }
    }

    @Override
    protected void initData() {
        if (sImgPath == null || sImgPath.isEmpty()) {
            mRetBitmap = sBitmap;
        } else {
            mRetBitmap = ImageUtils.getBitmap(sImgPath);
        }
        mFuncItems = getFuncData();
        mDataBinding.imageViewTouch.setImageBitmap(mRetBitmap);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);

        oldPosition = pos;
        showFragmentByFunc(mFuncItems.get(pos));
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(com.stark.imgedit.R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        ImageUtils.save2Album(mRetBitmap, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(com.stark.imgedit.R.string.save_success));
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    private List<FuncBean> getFuncData() {
        if (mFuncItems != null) {
            return mFuncItems;
        }
        List<FuncBean> funcBeans = new ArrayList<>();
        mFuncItems = funcBeans;
        FuncBean funcBean = null;
        funcBean = new FuncBean(FuncBean.FUNC_BEUITY, getString(R.string.beauty_text), R.drawable.edit_sel);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_FILTER, getString(R.string.filter_text), R.drawable.edit_sel);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(PicEditActivity.MODE_ENHANCE, getString(R.string.enhance_text), R.drawable.edit_sel);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_DRAW, getString(R.string.paint_text), R.drawable.edit_sel);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_EOMJ, getString(R.string.sticker_text), R.drawable.edit_sel);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_COLOR_TUNE, getString(R.string.color_tune), R.drawable.edit_sel);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_TEXT, getString(R.string.pic_text), R.drawable.edit_sel);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_ROTATION, getString(R.string.rotate_text), R.drawable.edit_sel);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_CROP, getString(R.string.crop_text), R.drawable.edit_sel);
        funcBeans.add(funcBean);

        return funcBeans;
    }

    private void showFragmentByFunc(FuncBean funcBean) {
        if (funcBean == null) {
            return;
        }
        if (oldPosition != pos) {
            clearSelection();
        }
        View targetChild = mDataBinding.llPicEditContainer.getChildAt(pos);
        targetChild.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                targetChild.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int scrollX = targetChild.getLeft() - (mDataBinding.svPicEditBottom.getWidth() / 2);
                mDataBinding.svPicEditBottom.smoothScrollTo(scrollX, 0);
            }
        });
        showEdit(funcBean.getName());
        switch (funcBean.getFunc()) {
            case BeautyFragment.INDEX:
                showBeautyFragment();
                mDataBinding.tvPicBeauty.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicBeauty.setVisibility(View.VISIBLE);
                break;
            case FilterFragment.INDEX:
                showFilterFragment();
                mDataBinding.tvPicFilter.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicFilter.setVisibility(View.VISIBLE);
                break;
            case EnhanceFragment.INDEX:
                showEnhanceFragment();
                mDataBinding.tvPicEnhance.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicEnhance.setVisibility(View.VISIBLE);
                break;
            case PaintFragment.INDEX:
                showPaintFragment();
                mDataBinding.tvPicPaint.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicPaint.setVisibility(View.VISIBLE);
                break;
            case StickerFragment.INDEX:
                showStickerFragment();
                mDataBinding.tvPicSticker.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicSticker.setVisibility(View.VISIBLE);
                break;
            case ColorTuneFragment.INDEX:
                showColorTuneFragment();
                mDataBinding.tvPicColorTune.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicColorTune.setVisibility(View.VISIBLE);
                break;
            case AddTextFragment.INDEX:
                showAddTextFragment();
                mDataBinding.tvPicText.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicText.setVisibility(View.VISIBLE);
                break;
            case RotateFragment.INDEX:
                showRotateFragment();
                mDataBinding.tvPicRotate.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicRotate.setVisibility(View.VISIBLE);
                break;
            case CropFragment.INDEX:
                showCropFragment();
                mDataBinding.tvPicCrop.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicCrop.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    /**
     * 点击右下角“勾”后的处理
     */
    private void clickApply() {
        switch (mode) {
            case MODE_BEAUTY:
                mBeautyFragment.applyBeautyImage();
                break;
            case MODE_FILTER:
                mFilterFragment.applyFilterImage();
                break;
            case MODE_ENHANCE:
                mEnhanceFragment.applyEnhanceImage();
                break;
            case MODE_PAINT:
                mPaintFragment.applyPaintImage();
                break;
            case MODE_STICKERS:
                mStickerFragment.applyStickers();
                break;
            case MODE_COLOR_TUNE:
                mColorTuneFragment.applyColorTune();
                return;
            case MODE_TEXT:
                mAddTextFragment.applyTextImage();
                break;
            case MODE_ROTATE:
                mRotateFragment.applyRotateImage();
                return;
            case MODE_CROP:
                mCropFragment.applyCropImage();
                return;
            default:
                break;
        }
    }

    private void showBeautyFragment() {
        if (mBeautyFragment == null) {
            mBeautyFragment = BeautyFragment.newInstance();
        } else {
            mBeautyFragment.onShow();
        }
        showFragment(mBeautyFragment);
    }

    private void showFilterFragment() {
        if (mFilterFragment == null) {
            mFilterFragment = FilterFragment.newInstance();
        } else {
            mFilterFragment.onShow();
        }
        showFragment(mFilterFragment);
    }

    private void showEnhanceFragment() {
        if (mEnhanceFragment == null) {
            mEnhanceFragment = EnhanceFragment.newInstance();
        } else {
            mEnhanceFragment.onShow();
        }
        showFragment(mEnhanceFragment);
    }

    private void showPaintFragment() {
        if (mPaintFragment == null) {
            mPaintFragment = PaintFragment.newInstance();
        } else {
            mPaintFragment.onShow();
        }
        showFragment(mPaintFragment);
    }

    private void showStickerFragment() {
        if (mStickerFragment == null) {
            mStickerFragment = StickerFragment.newInstance();
        } else {
            mStickerFragment.onShow();
        }
        showFragment(mStickerFragment);
    }

    private void showColorTuneFragment() {
        if (mColorTuneFragment == null) {
            mColorTuneFragment = ColorTuneFragment.newInstance();
        } else {
            mColorTuneFragment.onShow();
        }
        showFragment(mColorTuneFragment);
    }

    private void showAddTextFragment() {
        if (mAddTextFragment == null) {
            mAddTextFragment = AddTextFragment.newInstance();
        } else {
            mAddTextFragment.onShow();
        }
        showFragment(mAddTextFragment);
    }

    private void showRotateFragment() {
        if (mRotateFragment == null) {
            mRotateFragment = RotateFragment.newInstance();
        } else {
            mRotateFragment.onShow();
        }
        showFragment(mRotateFragment);
    }

    private void showCropFragment() {
        if (mCropFragment == null) {
            mCropFragment = CropFragment.newInstance();
        } else {
            mCropFragment.onShow();
        }
        showFragment(mCropFragment);
    }

    private void showFragment(BaseEditFragment baseEditFragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.flFragmentContainer, baseEditFragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    public Bitmap getMainBit() {
        return mRetBitmap;
    }

    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) {
        if (newBit == null) {
            return;
        }

        if (mRetBitmap != newBit) {
            mRetBitmap = newBit;
            mImgView.setImageBitmap(mRetBitmap);
            mImgView.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    private void showEdit(String name) {
        mDataBinding.rlTitle.setVisibility(View.GONE);
        mDataBinding.rlFunction.setVisibility(View.VISIBLE);
        mDataBinding.flFragmentContainer.setVisibility(View.VISIBLE);
        mDataBinding.tvFunctionTitle.setText(name);
    }

    public void showFunc() {
        mDataBinding.rlTitle.setVisibility(View.VISIBLE);
        mDataBinding.rlFunction.setVisibility(View.GONE);
        mDataBinding.flFragmentContainer.setVisibility(View.INVISIBLE);
    }

    private void clearSelection() {
        mDataBinding.tvPicBeauty.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicBeauty.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicFilter.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicFilter.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicEnhance.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicEnhance.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicPaint.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicPaint.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicSticker.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicSticker.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicColorTune.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicColorTune.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicText.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicText.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicRotate.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicRotate.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicCrop.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicCrop.setVisibility(View.INVISIBLE);


        if (oldPosition == 0) {
            mBeautyFragment.backToMain();
        }
        if (oldPosition == 1) {
            mFilterFragment.backToMain();
        }
        if (oldPosition == 2) {
            mEnhanceFragment.backToMain();
        }
        if (oldPosition == 3) {
            mPaintFragment.backToMain();
        }
        if (oldPosition == 4) {
            mStickerFragment.backToMain();
        }
        if (oldPosition == 5) {
            mColorTuneFragment.backToMain();
        }
        if (oldPosition == 6) {
            mAddTextFragment.backToMain();
        }
        if (oldPosition == 7) {
            mRotateFragment.backToMain();
        }
        if (oldPosition == 8) {
            mCropFragment.backToMain();
        }
    }

    private void cancelEdit() {
        mDataBinding.tvPicBeauty.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicBeauty.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicFilter.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicFilter.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicEnhance.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicEnhance.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicPaint.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicPaint.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicSticker.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicSticker.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicColorTune.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicColorTune.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicText.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicText.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicRotate.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicRotate.setVisibility(View.INVISIBLE);
        mDataBinding.tvPicCrop.setTextColor(Color.parseColor("#9C9C9C"));
        mDataBinding.ivPicCrop.setVisibility(View.INVISIBLE);

        switch (mode) {
            case MODE_BEAUTY:
                mBeautyFragment.backToMain();
                return;
            case MODE_FILTER:
                mFilterFragment.backToMain();
                return;
            case MODE_ENHANCE:
                mEnhanceFragment.backToMain();
                return;
            case MODE_PAINT:
                mPaintFragment.backToMain();
                return;
            case MODE_STICKERS:
                mStickerFragment.backToMain();
                return;
            case MODE_COLOR_TUNE:
                mColorTuneFragment.backToMain();
                return;
            case MODE_TEXT:
                mAddTextFragment.backToMain();
                return;
            case MODE_ROTATE:
                mRotateFragment.backToMain();
                return;
            case MODE_CROP:
                mCropFragment.backToMain();
                return;
            default:
                break;
        }
    }

}